package com.jing.system.comm;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.time.DateUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import weibo4j.model.User;
import weibo4j.model.UserWapper;
import weibo4j.model.WeiboException;

import com.jing.system.comm.contants.WeiboCons;
import com.jing.system.comm.enums.FansAttentionType;
import com.jing.system.comm.enums.GenderType;
import com.jing.system.utils.DateUtil;
import com.jing.taobao.pojo.user.TaobaoUser;
import com.jing.weibo.pojo.fans.Fansattention;
import com.jing.weibo.pojo.user.Synchrolog;
import com.jing.weibo.pojo.user.UserInfo;
import com.jing.weibo.service.fans.FansAttentionService;
import com.jing.weibo.service.user.SynchrologService;
import com.jing.weibo.service.user.UserInfoService;
import com.jing.weibo.ws.sina.FriendshipsService;

/**
 * Base Controller
 * @author jing.yue
 * @version 2012/08/29 1.0.0
 */
public class BaseController {

	private static final Logger logger = Logger.getLogger(BaseController.class);

	public static final String SUCCESS = "success";
	public static final String ERROR = "error";
	/** 管理员错误页面[admin/error] */
	public static final String ERROR_ADMIN = "admin/error";
	/** 调用微博接口异常 */
	public static final String ERROR_WEIBO = "error_weibo";
	/** 您没有开启互粉功能 */
	public static final String ERROR_ISOPENMP = "error_isopenmp";
	/** 您没有开启同城互粉功能 */
	public static final String ERROR_ISOPENCWMP = "error_isopencwmp";
	/** 您不是管理员用户 */
	public static final String ERROR_NOT_ADMIN = "error_not_admin";
	/** 您不是开发者 */
	public static final String ERROR_NOT_DEVELOPER = "error_not_developer";
	/** 用户没有登录 */
	public static final String ERROR_NOT_LOGIN = "error_not_login";
	/** 用户在指定周期内互粉过了 */
	public static final String ERROR_USER_FREEZE_MP = "error_user_freeze_mp";
	/** 是否需要同步Session中的用户信息 */
	public static Boolean isSynchroSessionUserinfo = false;

	@Autowired
	private SynchrologService synchrologService;
	@Autowired
	private FriendshipsService friendshipsService;
	@Autowired
	private UserInfoService userInfoService;
	@Autowired
	private FansAttentionService fansAttentionService;

	public final static String SESSION_USER_KEY = "userInfo";
	public final static String SESSION_USER_TAOBAO_KEY = "userInfoTaobao";
	public final static String SESSION_INVITEFRIENDINFO = "inviteFriendInfo";
	public final static String SESSION_FORCELOGIN = "forcelogin";
	public final static String SESSION_LOGIN_TYPE = "loginType";

	/**
	 * 修改同步记录时间
	 * @param request
	 * @param fansAttentionType
	 * @throws Exception
	 */
	public void updateSynchrologInfo(HttpServletRequest request, FansAttentionType fansAttentionType) throws Exception {
		UserInfo userInfo = getSessionUser(request);
		Synchrolog synchrolog = new Synchrolog();
		synchrolog.setUsername(userInfo.getUsername());
		synchrolog.setSynchrotable(fansAttentionType.getCode());
		Synchrolog sl = synchrologService.findByUserNameSynchrotable(synchrolog);
		//有数据
		if(sl != null) {
			//根据用户名和类型删除记录
			synchrologService.deleteSynchrolog(sl);

			//根据用户名和类型删除粉丝等记录
			Fansattention fansattention = new Fansattention();
			fansattention.setUsername(userInfo.getUsername());
			fansattention.setType(fansAttentionType.getCode());
			fansAttentionService.deleteFansattention(fansattention);

		}
	}

	/**
	 * 根据类型同步记录到数据库
	 * @param request
	 * @param synchroType
	 * @throws Exception
	 */
	public void synchrologInfo(HttpServletRequest request, FansAttentionType fansAttentionType) throws Exception {
		UserInfo userInfo = getSessionUser(request);

		//判断是否同步过
		Synchrolog synchrolog = new Synchrolog();
		synchrolog.setUsername(userInfo.getUsername());
		synchrolog.setSynchrotable(fansAttentionType.getCode());
		Synchrolog sl = synchrologService.findByUserNameSynchrotable(synchrolog);

		Date querytime = DateUtils.addMinutes(DateUtil.getTime(), WeiboCons.UPDATE_PAST_DUE_DATE);
		//超过时间则从新获取数据[默认为25分钟]
		if(sl != null && sl.getSynchrotime().compareTo(querytime) == -1) {
			updateSynchrologInfo(request, fansAttentionType);
			sl = null;
		}
		//不存在记录
		if(sl == null) {
			sl = new Synchrolog();
			sl.setNextcursor("0");
			String nextcursor = synchroFansAttention(userInfo, fansAttentionType, sl);
			if(nextcursor != null) {
				//添加用户同步记录
				synchrolog.setNextcursor(nextcursor);
				synchrologService.saveSynchrolog(synchrolog);
			}

		}
		//有数据
		else if(sl != null) {
			String nextcursor = synchroFansAttention(userInfo, fansAttentionType, sl);
			if(nextcursor != null) {
				//根据用户名和同步的表名修改用户同步记录信息
				sl.setNextcursor(nextcursor);
				synchrologService.updateSynchrolog(sl);
			}

		}
	}

	/**
	 * 保存信息
	 * @param username
	 * @param fansAttentionType
	 * @param userWapper
	 * @throws Exception
	 */
	private void saveFansattention(String username, FansAttentionType fansAttentionType, UserWapper userWapper) throws Exception {
		for (User user : userWapper.getUsers()) {
			//设置信息
			Fansattention fansattention = BaseController.setFansattention(user, username, fansAttentionType.getCode());

			//判断数据库中是否存在
			if(fansAttentionService.findByUsernameFansnameType(fansattention) != null) {
				fansAttentionService.updateFansattention(fansattention);
			}
			else {
				//保存粉丝信息
				fansAttentionService.saveFansattention(fansattention);
			}
		}
	}

	/**
	 * 同步粉丝信息
	 * @param userInfo
	 * @param fansAttentionType
	 * @param synchrolog
	 * @throws WeiboException, Exception
	 */
	private String synchroFansAttention(UserInfo userInfo, FansAttentionType fansAttentionType, Synchrolog synchrolog) throws WeiboException, Exception {
		//为空或-1则不查询粉丝信息
		if(synchrolog.getNextcursor() == null || "-1".equals(synchrolog.getNextcursor().trim())) {
			logger.info(userInfo.getNickname() + ":已经获取全部" + fansAttentionType.getText() + "完成!");
			return null;
		}
		UserWapper userWapper = null;
		switch (fansAttentionType) {
		case TYPE_ATTENTION:

			//根据用户和类型删除历史记录
			userWapper = friendshipsService.getFriendsByID(userInfo.getUsername(), WeiboCons.WEIBO_USER_PAGE_SIZE, Integer.valueOf(synchrolog.getNextcursor()), userInfo.getToken());
			//不存在数据
			if(userWapper == null || userWapper.getUsers() == null || userWapper.getUsers().size() == 0) {
				return null;
			}
			//不存在下一页
			else if(userWapper.getNextCursor() <= 0l) {
				saveFansattention(userInfo.getUsername(), fansAttentionType, userWapper);
				return "-1";
			}
			saveFansattention(userInfo.getUsername(), fansAttentionType, userWapper);
			return Long.toString(userWapper.getNextCursor());

		case TYPE_FANS:

			//获取所有粉丝
			userWapper = friendshipsService.getFollowersById(userInfo.getUsername(), WeiboCons.WEIBO_USER_PAGE_SIZE, Integer.valueOf(synchrolog.getNextcursor()), userInfo.getToken());
			//不存在数据
			if(userWapper == null || userWapper.getUsers() == null || userWapper.getUsers().size() == 0) {
				return null;
			}
			//不存在下一页
			else if(userWapper.getNextCursor() <= 0l) {
				saveFansattention(userInfo.getUsername(), fansAttentionType, userWapper);
				return "-1";
			}
			saveFansattention(userInfo.getUsername(), fansAttentionType, userWapper);
			return Long.toString(userWapper.getNextCursor());

		}
		return null;
	}

	/**
	 * 设置信息
	 * @param user
	 * @param uid
	 * @param type
	 * @return
	 */
	public static Fansattention setFansattention(User user, String uid, String type) {
		Fansattention fansattention = new Fansattention();
		//用户名
		fansattention.setUsername(uid);
		//粉丝关注的用户名
		fansattention.setFansattentionusername(user.getId());
		//类型[0粉丝/1关注/2互相关注]
		fansattention.setType(type);
		//粉丝关注的昵称
		fansattention.setNickname(user.getScreenName());
		//关注数
		fansattention.setAttentionnum(Integer.toString(user.getFriendsCount()));
		//粉丝数
		fansattention.setFansnum(Integer.toString(user.getFollowersCount()));
		//微博数
		fansattention.setWeibonum(Integer.toString(user.getStatusesCount()));
		//头像
		fansattention.setImg(user.getavatarLarge());
		//性别
		fansattention.setGender(GenderType.getCodeByText(user.getGender()));
		//V认证
		fansattention.setVerified(String.valueOf(user.isVerified()));
		//该用户是否关注当前登录用户
		fansattention.setFollowme(Boolean.toString(user.isFollowMe()));
		//当前登录用户是否关注了该用户
		fansattention.setFollowing(Boolean.toString(user.isFollowing()));
		return fansattention;
	}

	/**
	 * 从Session中获取用户信息
	 * @param request
	 * @return
	 */
	public UserInfo getSessionUser(HttpServletRequest request) {
		UserInfo userInfo = (UserInfo) request.getSession().getAttribute(SESSION_USER_KEY);
		if(isSynchroSessionUserinfo) {
			//从数据库中获取信息
			try {
				userInfo = userInfoService.findByUserName(userInfo.getUsername());
				setSessionUser(request, userInfo);
			} catch (Exception e) {
				logger.error("获取用户信息异常!", e);
			}
		}
		return userInfo;
	}

	/**
	 * 设置授权了的用户信息到Session中
	 * @param request
	 * @param user
	 */
	public void setSessionUser(HttpServletRequest request, UserInfo user) {
		//设置下次不在同步用户信息
		isSynchroSessionUserinfo = false;
		request.getSession().setAttribute(SESSION_USER_KEY, user);
	}

	/**
	 * 移除授权了的Session中的用户信息
	 * @param request
	 */
	public void removeSessionUser(HttpServletRequest request) {
		request.getSession().removeAttribute(SESSION_USER_KEY);
	}

	/**
	 * 设置值到Session中
	 * @param request
	 * @param key
	 * @param value
	 */
	public void setSession(HttpServletRequest request, String key, String value) {
		request.getSession().setAttribute(key, value);
	}

	/**
	 * 获取Session中的值
	 * @param request
	 * @param key
	 * @return
	 */
	public Object getSession(HttpServletRequest request, String key) {
		return request.getSession().getAttribute(key);
	}

	/**
	 * 移除Session中的信息
	 * @param request
	 * @param key
	 */
	public void removeSession(HttpServletRequest request, String key) {
		request.getSession().removeAttribute(key);
	}

	/**
	 * 从Session中获取淘宝用户信息
	 * @param request
	 * @return
	 */
	public TaobaoUser getSessionTaobaoUser(HttpServletRequest request) {
		TaobaoUser taobaoUser = (TaobaoUser) request.getSession().getAttribute(SESSION_USER_TAOBAO_KEY);
		return taobaoUser;
	}

	/**
	 * 设置授权了的淘宝用户信息到Session中
	 * @param request
	 * @param user
	 */
	public void setSessionTaobaoUser(HttpServletRequest request, TaobaoUser taobaoUser) {
		request.getSession().setAttribute(SESSION_USER_TAOBAO_KEY, taobaoUser);
	}

	/**
	 * 移除授权了的Session中的淘宝用户信息
	 * @param request
	 */
	public void removeSessionTaobaoUser(HttpServletRequest request) {
		request.getSession().removeAttribute(SESSION_USER_TAOBAO_KEY);
	}
}